<template>
  <div class="chat-page">
    <!-- 左侧导航栏 -->
    <div class="sidebar">
      <div class="logo" @click="goHome">
        <h2>AI聊天</h2>
      </div>
       <h2 class="menu-title">历史记录</h2>
      <ul class="menu">
        <li><a href="#" @click.prevent="createNewSession" class="active">+ 新聊天</a></li>
        <!-- 会话历史列表 -->
        <li 
          v-for="(session, index) in sessionHistory" 
          :key="index" 
          class="session-item"
          :class="{ active: session.id === activeSessionId }"
        >
          <div @click="loadSession(session)">
            {{ session.title }}
          </div>
          <button class="delete-btn" @click="deleteSession(session.id, index)">×</button>
        </li>
      </ul>
    </div>

    <!-- 中间聊天区域 -->
    <div class="chat-area">
     <!-- 聊天记录显示区域 -->
      <div class="chat-messages">
        <div 
          v-for="(message, index) in messages" 
          :key="index" 
          :class="['message', message.type]"
        >
          <div class="content" v-html="formatMessageContent(message.content)"></div>
          <div class="timestamp">{{ formatMessageTime(message.timestamp || new Date()) }}</div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="chat-input">
        <input 
          type="text" 
          :placeholder="inputPlaceholder" 
          @focus="clearPlaceholder"
          v-model="userInput"
          @keyup.enter="sendMessage"
        />
        <button @click="sendMessage">发送</button>
      </div>
    </div>
  </div>
</template>

<script>
import { marked } from 'marked'; 

export default {
  name: 'ChatPage',
  data() {
    return {
      inputPlaceholder: '你可以询问任何问题',
      userInput: '',
      messages: [],
      conversationId: '',
      sessionHistory: [], // 存储会话历史
      activeSessionId: null // 当前选中的会话ID
    };
  },
  created() {
    // 页面加载时创建新的会话并获取会话历史列表
    this.fetchSessionHistory();
    this.createNewSession();
  },
  methods: {
    goHome() {
      this.$router.push({ name: 'home' });
    },
    clearPlaceholder() {
      this.inputPlaceholder = '';
    },
    formatMessageContent(content) {
      // 使用 marked 库将 Markdown 转换为 HTML
      return marked(content);
    },
    formatMessageTime(timestamp) {
      // 格式化消息时间
      const date = new Date(timestamp);
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      return `${hours}:${minutes}`;
    },
    // 生成唯一的会话ID
    generateConversationId() {
      // 随机生成8位数字的会话ID并返回，要求必须是纯数字
      return Math.random().toString().slice(2, 10);
    },
    // 创建新会话
    createNewSession() {
      // 清空当前消息
      this.messages = [];
      // 生成新的会话ID
      this.conversationId = this.generateConversationId();
      
      // 创建新会话对象，直接使用会话ID作为标题
      const newSession = {
        id: this.conversationId,
        title: this.conversationId
      };
      
      // 将新会话添加到会话历史中
      this.sessionHistory.unshift(newSession);
      
      // 设置新创建的会话为激活状态
      this.activeSessionId = this.conversationId;
      
      console.log('创建新会话:', this.conversationId);
    },
    // 加载指定会话
    loadSession(session) {
      // 设置当前选中的会话ID
      this.activeSessionId = session.id;
      // 同时更新当前会话ID，确保发送消息时使用正确的会话ID
      this.conversationId = session.id;
      
      // 使用会话ID查询对应的聊天记录
      console.log('加载会话ID:', session.id);
      
      // 从后端获取该会话的聊天记录
        fetch(`http://localhost:8080/ai/history/chat/${session.id}`)
        .then(response => {
          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }
          return response.json();
        })
        .then(result => {
          console.log('获取会话历史成功:', result);
          // 清空当前消息
          this.messages = [];
          
          // 检查结果是否为数组，如果不是则包装成数组
          if (Array.isArray(result)) {
            // 将获取到的聊天记录添加到消息列表中
            result.forEach(message => {
              this.messages.push({
                type: message.type,
                content: message.content,
                timestamp: new Date() // 添加时间戳
              });
            });
          } else if (result && typeof result === 'object') {
            // 如果结果是对象，尝试检查它是否包含消息数组
            console.log('后端返回的对象:', result);
            // 可以根据实际返回的数据结构调整这里的逻辑
          }
        })
        .catch(error => {
          console.log('获取会话历史失败:', error);
          // 清空当前消息
          this.messages = [];
        });
    },
    // 删除指定会话
    deleteSession(sessionId, index) {
      调用后端删除接口
      fetch(`http://localhost:8080/ai/history/chat/${sessionId}`, {
        method: 'DELETE'
      })
        .then(response => {
          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }
          // 从本地会话历史列表中移除
          this.sessionHistory.splice(index, 1);
          
          // 如果删除的是当前激活的会话，则清空消息并创建新会话
          if (this.activeSessionId === sessionId) {
            this.messages = [];
            this.activeSessionId = null;
          }
          
          console.log('会话删除成功:', sessionId);
        })
        .catch(error => {
          console.log('删除会话失败:', error);
        });
    },
    sendMessage() {
      // 如果输入为空则不发送
      if (!this.userInput.trim()) return;
      
      // 保存用户输入
      const userMessage = this.userInput;
      
      // 添加用户消息到聊天记录
      this.messages.push({
        type: 'user',
        content: userMessage,
        timestamp: new Date()
      });
      
      // 清空输入框
      this.userInput = '';
      
      // 调用后端API
      this.callBackendAPI(userMessage);
    },
    callBackendAPI(message) {
      var requestOptions = {
        method: 'GET',
        redirect: 'follow'
      };

        fetch(`http://localhost:8080/ai/chatAi?message=${encodeURIComponent(message)}&conversationId=${encodeURIComponent(this.conversationId)}`, requestOptions)
        .then(response => response.text())
        .then(result => {
          // 将后端返回的结果添加到聊天记录
          this.messages.push({
            type: 'ai',
            content: result,
            timestamp: new Date()
          });
          
          // 更新会话标题为第一条消息的内容（如果当前会话标题还是默认值）
          const sessionIndex = this.sessionHistory.findIndex(s => s.id === this.conversationId);
          if (sessionIndex !== -1 && this.sessionHistory[sessionIndex].title === this.conversationId) {
            this.sessionHistory[sessionIndex].title = message.substring(0, 15) + (message.length > 15 ? '...' : '');
          }
        })
        .catch(error => {
          console.log('error', error);
          // 错误处理，显示错误信息
          this.messages.push({
            type: 'error',
            content: '抱歉，消息发送失败，请稍后重试。',
            timestamp: new Date()
          });
        });
    },
    // 从后端获取会话历史列表
    fetchSessionHistory() {
       fetch("http://localhost:8080/ai/history/chat")
       .then(response => response.json())
        .then(result => {
          console.log('会话历史:', result);
          // 将获取到的会话历史设置为返回的数据，直接使用会话ID作为标题
          this.sessionHistory = result.map(sessionId => ({
            id: sessionId,
            title: sessionId
          }));
        })
        .catch(error => {
          console.log('获取会话历史失败:', error.response);
        });
    }
  }
};
</script>

<style scoped>
.active{
  background-color: #007bff;
  /* 文字居中 */
  text-align: center;
}
.chat-page {
  display: flex;
  height: 100vh;
}

.sidebar {
  width: 200px; /* 设置固定宽度 */
  background-color: #f4f4f4;
  padding: 20px;
  flex-shrink: 0; /* 确保不收缩 */
  /* 使用更兼容的写法 */
  height: -webkit-fill-available;
  overflow: auto;
}

.menu-title {
  text-align: center;
  font-weight: bold;
}

.logo {
  font-size: 20px;
  margin-bottom: 20px;
  cursor: pointer;
  color: #ec0b0b;
  /* 文字居中显示 */
  text-align: center;
}

.menu {
  margin-top: 20px;
  font-size: 16px;
  /* 左边距 */
  margin-left: -45px;
}

.menu li {
  list-style: none;
  margin-bottom: 5px; /* 减少底部间距 */
}

.menu a {
  text-decoration: none;
  color: #333;
  display: block; /* 确保链接块级显示 */
  padding: 8px 10px; /* 调整内边距 */
}

.chat-area {
  flex-grow: 1; /* 占据剩余空间 */
  padding: 20px;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  min-height: 100vh;
}

.chat-messages {
  flex-grow: 1;
  overflow-y: auto;
  margin-bottom: 20px;
}

.message {
  padding: 10px 15px;
  margin-bottom: 10px;
  border-radius: 15px;
  max-width: 80%;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.message.user {
  background-color: #007bff;
  color: white;
  margin-left: auto;
}

.message.ai {
  background-color: #f1f1f1;
  color: #333;
  margin-right: auto;
}

.message.error {
  background-color: #f8d7da;
  color: #721c24;
  margin-right: auto;
}

.message-content {
  line-height: 1.5;
  word-wrap: break-word;
}

.timestamp {
  font-size: 12px;
  color: #999;
  text-align: right;
  margin-top: 5px;
  opacity: 0.7;
}

.chat-header h2 {
  text-align: center;
}

.chat-input {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
}

.chat-input input {
  width: 80%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: white;
  color: black;
}

.chat-input button {
  padding: 10px 20px;
  border: none;
  background-color: #007bff;
  color: white;
  border-radius: 5px;
  cursor: pointer;
  margin-left: 10px;
  transition: background-color 0.3s ease;
}

.chat-input button:hover {
  background-color: #0056b3;
}

.session-item {
  padding: 8px 10px; /* 调整内边距 */
  cursor: pointer;
  border-bottom: 1px solid #ddd;
  font-size: 14px; /* 调整字体大小 */
  text-align: center;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.session-item:hover {
  background-color: #e9e9e9;
}

.session-item.active {
  background-color: #007bff;
  color: white;
}

.delete-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.delete-btn:hover {
  color: #ff0000;
  background-color: rgba(255, 0, 0, 0.1);
  border-radius: 50%;
}

/* 动画效果 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message {
  animation: fadeInUp 0.5s ease-out forwards;
}
</style>